﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.Common.AssistClass
{
    /// <summary>
    /// 反射赋值
    /// </summary>
    public class ObjectReflection
    {
        public static PropertyInfo[] GetPropertyInfos(Type type)
        {
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }
        /// <summary>
        /// 为某个类的属性反射赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="evaluationName"></param>
        /// <param name="evaluationValue"></param>
        /// <param name="isChangeDoubleToDateTime"></param>
        public static void AutoEvaluation<T>(T t,String evaluationName, Object evaluationValue,Boolean isChangeDoubleToDateTime = false)
        {
            Type target = t.GetType();
            PropertyInfo evaluationProperty = target.GetProperty(evaluationName);
            if (evaluationProperty.CanWrite)
            {
                if(evaluationValue != null && evaluationValue.ToString() != "")
                {
                    if (isChangeDoubleToDateTime && evaluationProperty.PropertyType.Name == "DateTime")
                    {
                        try
                        {
                            DateTime baseTime = new DateTime(1899, 12, 30);
                            Double addTime = Double.Parse(evaluationValue.ToString());
                            evaluationValue = baseTime.AddDays(addTime).ToString();
                        }
                        catch
                        {
                            evaluationValue = DateTime.MaxValue;
                        }
                    }

                    evaluationValue = Convert.ChangeType(evaluationValue.ToString(), evaluationProperty.PropertyType);
                }
                else
                {
                    switch (evaluationProperty.PropertyType.Name)
                    {
                        case "Double":
                            evaluationValue = 0.0;
                            break;
                        case "Int32":
                            evaluationValue = 0;
                            break;
                        case "Int64":
                            evaluationValue = 0;
                            break;
                        case "Boolean":
                            evaluationValue = false;
                            break;
                        case "DateTime":
                            evaluationValue = DateTime.Parse("9999-12-31");
                            break;
                        default:
                            evaluationValue = null;
                            break;
                    }
                }
                

                evaluationProperty.SetValue(t,evaluationValue);
            }
        }
    }

}
